<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class TableMonitorService
{
    /**
     * 检查所有分表的状态
     */
    public function checkAllShardedTables($baseTable)
    {
        $status = [
            'hot_tables' => [],
            'time_tables' => [],
            'missing_tables' => [],
            'corrupted_tables' => []
        ];
        
        // 检查热度分表
        for ($i = 1; $i <= 10; $i++) {
            $tableName = "{$baseTable}_hot_{$i}";
            $tableStatus = $this->checkTableStatus($tableName);
            
            if ($tableStatus['exists']) {
                $status['hot_tables'][$tableName] = $tableStatus;
            } else {
                $status['missing_tables'][] = $tableName;
            }
        }
        
        // 检查时间分表（最近12个月）
        $current = time();
        for ($i = 0; $i < 12; $i++) {
            $time = strtotime("-$i months", $current);
            $suffix = date('Ym', $time);
            $tableName = "{$baseTable}_{$suffix}";
            $tableStatus = $this->checkTableStatus($tableName);
            
            if ($tableStatus['exists']) {
                $status['time_tables'][$tableName] = $tableStatus;
            } else {
                $status['missing_tables'][] = $tableName;
            }
        }
        
        return $status;
    }
    
    /**
     * 检查单个表的状态
     */
    public function checkTableStatus($tableName)
    {
        $result = [
            'exists' => false,
            'row_count' => 0,
            'last_updated' => null,
            'size' => 0
        ];
        
        try {
            // 检查表是否存在
            $exists = DB::select("SHOW TABLES LIKE '{$tableName}'");
            
            if (!empty($exists)) {
                $result['exists'] = true;
                
                // 获取行数
                $count = DB::table($tableName)->count();
                $result['row_count'] = $count;
                
                // 获取最后更新时间
                $lastUpdated = DB::table($tableName)
                    ->orderBy('update_time', 'desc')
                    ->value('update_time');
                $result['last_updated'] = $lastUpdated;
                
                // 获取表大小（MySQL特定）
                $size = DB::select("
                    SELECT 
                        table_name AS `Table`,
                        round(((data_length + index_length) / 1024 / 1024), 2) `Size (MB)`
                    FROM information_schema.TABLES 
                    WHERE table_schema = DATABASE()
                    AND table_name = '{$tableName}'
                ");
                
                if (!empty($size)) {
                    $result['size'] = $size[0]->{'Size (MB)'};
                }
            }
        } catch (\Exception $e) {
            Log::error("检查表 {$tableName} 状态失败: " . $e->getMessage());
        }
        
        return $result;
    }
    
    /**
     * 自动修复缺失的表
     */
    public function repairMissingTables($baseTable)
    {
        $missingTables = [];
        
        // 检查热度分表
        for ($i = 1; $i <= 10; $i++) {
            $tableName = "{$baseTable}_hot_{$i}";
            $exists = DB::select("SHOW TABLES LIKE '{$tableName}'");
            
            if (empty($exists)) {
                $missingTables[] = $tableName;
                
                try {
                    DB::statement("CREATE TABLE {$tableName} LIKE {$baseTable}");
                    Log::info("已创建缺失的表: {$tableName}");
                } catch (\Exception $e) {
                    Log::error("创建表 {$tableName} 失败: " . $e->getMessage());
                }
            }
        }
        
        // 检查时间分表（最近6个月）
        $current = time();
        for ($i = 0; $i < 6; $i++) {
            $time = strtotime("-$i months", $current);
            $suffix = date('Ym', $time);
            $tableName = "{$baseTable}_{$suffix}";
            $exists = DB::select("SHOW TABLES LIKE '{$tableName}'");
            
            if (empty($exists)) {
                $missingTables[] = $tableName;
                
                try {
                    DB::statement("CREATE TABLE {$tableName} LIKE {$baseTable}");
                    Log::info("已创建缺失的表: {$tableName}");
                } catch (\Exception $e) {
                    Log::error("创建表 {$tableName} 失败: " . $e->getMessage());
                }
            }
        }
        
        return $missingTables;
    }
}
